<?php
namespace app\api\logic;

use app\api\consDir\ErrorConst;
use app\api\services\CollectService;
use app\api\services\GoodsService;
use app\api\services\RabbitMqService;
use app\api\services\ShopService;
use app\api\services\SystemUserService;
use app\common\libs\Singleton;
use app\common\models\Order\Order as OrderModel;
use app\common\models\Shop\Shop;
use app\common\models\Shop\ShopCategory;
use app\common\models\Shop\ShopComment;
use app\common\models\Shop\ShopPic;
use app\common\utils\CommonUtil;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 门店模块
 * Class MemberLogic
 * @package app\api\logic
 */
class ShopLogic extends BaseLogic
{
    use Singleton;

    public function addComment($shopId, $imgContent, $serveScore, $environmentScore, $costScore, $content, $orderNo, $isAnonymity): bool
    {
        $allScore = bcdiv(($serveScore + $environmentScore + $costScore), 3);
        $isBad    = $allScore <= 2 ? 1 : 0;

        $isImg = empty($imgContent) ? 0 : 1;

        $data = [
            'shop_id'           => $shopId,
            'user_id'           => $this->userinfo->id,
            'is_img'            => $isImg,
            'is_bad'            => $isBad,
            'serve_score'       => $serveScore,
            'environment_score' => $environmentScore,
            'cost_score'        => $costScore,
            'all_score'         => $allScore,
            'content'           => $content,
            'img_content'       => $imgContent,
            'order_no'          => $orderNo,
            'is_anonymity'      => $isAnonymity,
        ];
        ShopComment::getInstance()->startTrans();
        try {
            ShopComment::getInstance()->insert($data);
            //更新订单是否评论状态
            OrderModel::getInstance()
                ->where(['user_id' => $this->userinfo->id, 'order_no' => $orderNo])
                ->update([
                    'is_comment' => 1,
                    'update_at'  => date('Y-m-d H:i:s'),
                ]);
            //加入队列处理评分
            $event["exchange"] = config('rabbitmq.info_queue');
            $data              = [
                'id'                => $shopId,
                'serve_score'       => $serveScore,
                'environment_score' => $environmentScore,
                'cost_score'        => $costScore,
            ];
            RabbitMqService::send($event, ['type' => 'shop_comment', 'data' => $data]);
        } catch (\Exception $e) {
            ShopComment::getInstance()->rollback();
            return false;
        }
        ShopComment::getInstance()->commit();
        return true;
    }

    /**
     * @param $shopId
     * @param $typeId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function shopPic($shopId, $typeId): array
    {
        //获取店铺分类
        $typeInfo = ShopPic::getInstance()
            ->field('type_name,id,sort,imgs')
            ->where(['shop_id' => $shopId, 'deleted' => 0])
            ->order('sort desc')
            ->select();
        $typeInfo = empty($typeInfo) ? [] : $typeInfo->toArray();
        $arr      = [];
        foreach ($typeInfo as $k => &$val) {
            $imgList             = explode(',', $val['imgs']);
            $val['imgListCount'] = count($imgList);
            unset($val['imgs']);
            if ($typeId == 0) {
                if ($k == 0) {
                    $arr = $imgList;
                } else {
                    if ( ! empty($imgList)) {
                        $arr = array_merge($arr, $imgList);
                    }
                }
            } else {
                if ($typeId == $val['id']) {
                    $arr = $imgList;
                }
            }
        }
        return ['rows' => $arr, 'typeInfo' => $typeInfo];
    }

    public function shopComment($shopId, $page, $pageSize, $isBad, $isImg): array
    {
        $shopCommentCount = [
            'allCount' => ShopComment::getInstance()->where(['shop_id' => $shopId])->count(),
            'imgCount' => ShopComment::getInstance()->where(['shop_id' => $shopId, 'is_img' => 1])->count(),
            'badCount' => ShopComment::getInstance()->where(['shop_id' => $shopId, 'is_bad' => 1])->count(),
        ];
        $userComment = ShopService::getInstance()->getComment($shopId, $isImg, $isBad, $page, $pageSize);
        return ['rows' => $userComment, 'shopCommentCount' => $shopCommentCount];
    }

    public function shopInfo($shopId): array
    {
        $field = 'id,is_wifi,is_battery,is_shop,is_box,shop_type,shop_business_img,create_at';
        $info  = ShopService::getInstance()->shopInfo($shopId, $field);
        if (empty($info)) {
            CommonUtil::throwException(ErrorConst::NO_SHOP_ERROR, ErrorConst::NO_SHOP_ERROR_MSG);
        }
        $info['isCollect'] = CollectService::getInstance()->getUserCollectStatus(
            $this->userinfo->id,
            $info['shopType'],
            $shopId
        );

        $info['openStatus']    = 1;
        $info['openWeek']      = '周一到周日';
        $info['openTimeStart'] = '00:00';
        $info['openTimeEnd']   = '23:00';

        return $info;
    }

    /**
     * 店铺不存在返回空
     * @return [type] [description]
     */
    public function shopInfoByUid()
    {
        $info = ShopService::getInstance()->getShopInfo($this->userinfo->id, '*');
        return $info;
    }

    /**
     * @param $shopId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function shopDetail($param): array
    {
        // $where = [
        //     ['deleted', '=', 0],
        //     ['user_id', '=', $userId],
        // ];
        $where = array_merge($param, ['deleted' => 0]);
        $field = [
            'id as shop_id',
            'business_name',
            'business_type',
            'business_scope',
            'admin_account',
            'real_name',
            'corporate_id',
            'corporate_id_back',
            'corporate_id_front',
            'shop_idc',
            'corporate_id_back',
            'marks',

            'id',
            'shop_no',
            'shop_logo',
            'shop_name',
            'user_id',
            'city as send_city',
            'create_at',
            'content',
            'shop_banner',
            'per',
            'address',
            'latitude',
            'longitude',
            'shop_phone',
            'goods_count',
            'shop_type',
            'freight_insurance',
            'serve_score',
            'environment_score',
            'cost_score',
            'all_score',
            'shop_business_img',
            'open_week',
            ' open_time_start',
            'open_time_end',
            'open_status',

            'is_shop',
            'is_box',
            'is_battery',
            'is_wifi',
            'is_hot',
            'is_brand',
            'is_village',

            'kf_phone',
            'gxz_rate',
        ];

        $info = Shop::getInstance()
            ->where($where)
            ->field($field)
            ->order('id desc')
            ->find();
        $info = empty($info) ? [] : $info->toArray();
        if (empty($info)) {
            CommonUtil::throwException(
                ErrorConst::NO_SHOP_ERROR,
                ErrorConst::NO_SHOP_ERROR_MSG);
        }
        $shopId = $info['shopId'];
        // var_dump($shopId);exit;
        $info['isCollect'] = CollectService::getInstance()->getUserCollectStatus(
            $this->userinfo->id,
            $info['shopType'],
            $shopId);
        /*
        $info['isTrue'] = 1;
        $info['isOneTen'] = 1;
        $info['isFreightInsurance'] = 1;
        $info['isSeven'] = 1;
        $info['sendTime'] = 72;
        $info['openStatus'] = 1;
        $info['openWeek'] = '周一到周日';
        $info['openTimeStart'] = '00:00';
        $info['openTimeEnd'] = '23:00';
        */
        $info['goodsCount'] = ShopService::getInstance()->shopGoodsCount($info['id']);
        $shopCommentCount   = [
            'allCount' => ShopComment::getInstance()->where(['shop_id' => $info['id']])->count(),
            'imgCount' => ShopComment::getInstance()->where(['shop_id' => $info['id'], 'is_img' => 1])->count(),
            'badCount' => ShopComment::getInstance()->where(['shop_id' => $info['id'], 'is_bad' => 1])->count(),
        ];
        $userComment = ShopService::getInstance()->getComment($info['id'], 0, 0, 1, 10);
        $goodsInfo   = GoodsService::getInstance()
            ->goodsInfo($info['id'], 1, 10, 2, 0, '', 0, 'id,goods_title,goods_img,sell_price');
        $outlineGoodsInfo = GoodsService::getInstance()
            ->goodsInfo($info['id'], 1, 10, 1, 0, '', 0, 'goods_sales,goods_inventory,id,goods_title,goods_img,sell_price,market_price,gxz_rate');
        foreach ($outlineGoodsInfo as &$v) {
            $v['gxz'] = bcmul($v['sellPrice'], $v['gxzRate'] * 0.01, 2);
        }
        $shopPic = ShopService::getInstance()->shopPic($info['id'], 1, 3);

        $conf = sysconf('platform_conf');
        $conf = html_entity_decode($conf, ENT_QUOTES, 'UTF-8');
        $conf = json_decode($conf, true);

        return [
            'shopPic'          => $shopPic,
            'shopInfo'         => $this->shopInfoFilter($info),
            'userComment'      => $userComment,
            'shopCommentCount' => $shopCommentCount,
            'goodsInfo'        => $goodsInfo,
            'outlineGoodsInfo' => $outlineGoodsInfo,
            'merchantDomain'   => $conf['merchant_domain'] ?? ''
        ];
    }

    private function shopInfoFilter($info)
    {
        $info['marks']            = empty($info['marks']) ? [] : str2arr($info['marks']);
        $info['corporateIdBacks'] = [];
        if ($info['corporateIdBack']) {
            $corporateIdBacks = explode(',', $info['corporateIdBack']);
            for ($i = 0; $i < count($corporateIdBacks); $i++) {
                $info['corporateIdBacks'][$i]['type'] = 'image';
                $info['corporateIdBacks'][$i]['url']  = $corporateIdBacks[$i];
            }
        }

        $info['corporateIdFronts'] = [];
        if ($info['corporateIdFront']) {
            $corporateIdFronts = explode(',', $info['corporateIdFront']);
            for ($i = 0; $i < count($corporateIdFronts); $i++) {
                $info['corporateIdFronts'][$i]['type'] = 'image';
                $info['corporateIdFronts'][$i]['url']  = $corporateIdFronts[$i];
            }
        }

        $info['shopLogos'] = [];
        if ($info['shopLogo']) {
            $shopLogos = explode(',', $info['shopLogo']);
            for ($i = 0; $i < count($shopLogos); $i++) {
                $info['shopLogos'][$i]['type'] = 'image';
                $info['shopLogos'][$i]['url']  = $shopLogos[$i];
            }
        }

        $info['shopBusinessImgs'] = [];
        if ($info['shopBusinessImg']) {
            $shopBusinessImgs = explode(',', $info['shopBusinessImg']);
            for ($j = 0; $j < count($shopBusinessImgs); $j++) {
                $info['shopBusinessImgs'][$j]['type'] = 'image';
                $info['shopBusinessImgs'][$j]['url']  = $shopBusinessImgs[$j];
            }
        }

        $info['shopBanners'] = [];
        if ($info['shopBanner']) {
            $shopBanners = explode(',', $info['shopBanner']);
            for ($k = 0; $k < count($shopBanners); $k++) {
                $info['shopBanners'][$k]['type'] = 'image';
                $info['shopBanners'][$k]['url']  = $shopBanners[$k];
            }
        }
        return $info;
    }

    public function shopDetailAll($param): array
    {
        $where = array_merge($param, ['deleted' => 0]);
        $info  = Shop::getInstance()->where($where)->order('id desc')->find();
        $info  = empty($info) ? [] : $info->toArray();
        if (empty($info)) {
            CommonUtil::throwException(
                ErrorConst::NO_SHOP_ERROR,
                ErrorConst::NO_SHOP_ERROR_MSG
            );
        }
        return $this->shopInfoFilter($info);
    }

    /**
     * @param $shopType
     * @param $page
     * @param $pageSize
     * @param $sort
     * @param $lat
     * @param $lng
     * @param $keyword
     * @param $categoryId
     * @param $city
     * @return array
     */
    public function shopList($shopType, $page, $pageSize, $sort, $lat, $lng, $keyword, $categoryId, $city, $isHot, $isBrand, $isVillage, $minPer, $maxPer, $isWifi, $isStop, $isBox, $isBattery, $km): array
    {
        $list = ShopService::getInstance()->shopList($shopType, $page, $pageSize, $lat, $lng, $sort, $keyword, $categoryId, $city, $isHot, $isBrand, $isVillage, $minPer, $maxPer, $isWifi, $isStop, $isBox, $isBattery, $km);
        return ['rows' => $list];
    }

    public function addShop($data): bool
    {
        $shopInfo = ShopService::getInstance()->getShopInfo($this->userinfo->id);
        if ( ! empty($shopInfo)) {
            CommonUtil::throwException(ErrorConst::ADD_SHOP_ERROR, ErrorConst::ADD_SHOP_ERROR_MSG);
        }
        $data['user_id'] = $this->userinfo->id;
        ShopService::getInstance()->insertShop($data);
        return true;
    }

    /**
     * 店铺申请记录
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function apply($data)
    {
        $shopInfo = ShopService::getInstance()->getShopInfo($this->userinfo->id);
        if ( ! empty($shopInfo)) {
            CommonUtil::throwException(
                ErrorConst::ADD_SHOP_ERROR,
                ErrorConst::ADD_SHOP_ERROR_MSG
            );
        }
        $data['user_id'] = $this->userinfo->id;

        $where = [
            'is_deleted' => 0,
            'username'   => $data['admin_account'],
        ];
        $count = \think\facade\Db::table('shop_user')
            ->where($where)
            ->count();
        if ( ! empty($count)) {
            CommonUtil::throwException(
                ErrorConst::ACCOUNT_ERROR,
                ErrorConst::ACCOUNT_ERROR_MSG, // 账号已被绑定
            );
        }

        $row = \think\facade\Db::table('member_shop_apply')
            ->where('deleted', 0)
            ->where('user_id', $data['user_id'])
            ->find();
        // 0 审核中 1 成功 2 拒绝
        $status = $row['status'] ?? null;
        if ($status !== null) {
            return [
                'code'        => 0,
                'msg'         => 'success',
                'status'      => $status,
                'id'          => $row['id'],
                'auth_at'     => $row['auth_at'],
                'auth_remark' => $row['auth_remark'],
            ];
        }
        $id = \think\facade\Db::table('member_shop_apply')
            ->insertGetId($data);
        return [
            'code'        => 0,
            'msg'         => 'success',
            'status'      => 0,
            'id'          => $id,
            'auth_at'     => '',
            'auth_remark' => '',
        ];
    }

    public function updateShop($shopId, $shopData)
    {
        $info = ShopService::getInstance()->shopInfo($shopId);
        if (empty($info)) {
            CommonUtil::throwException(ErrorConst::NO_SHOP_ERROR, ErrorConst::NO_SHOP_ERROR_MSG);
        }
        //更新主表
        ShopService::getInstance()->updateUser($shopId, $shopData, $this->userinfo->id);
        //更新账号表
        SystemUserService::getInstance()->updateUser($shopId, $shopData);
        return true;
    }

    /**
     * [shopCategory description]
     * @param  [type] $online 1 线上  0 线下（非1）
     * @return [type]         [description]
     */
    public function shopCategory($online): array
    {
        $where = [
            'deleted'   => 0,
            // 店铺分类类型： 1线下 2线上
            'shop_type' => $online == 1 ? 2 : 1, // 1线下 2线上
            'status'    => 1,
        ];
        $list = ShopCategory::getInstance()
            ->where($where)
            ->order('sort desc')
            ->column('id,title,icon');
        return ['rows' => $list];
    }
}
